package com.top.mall.jetpack.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.SubscribeViewModel
import com.top.mall.entity.*
import com.top.mall.jetpack.ma.GoodsManager

open class GoodsViewModel(application: Application) : CartViewModel(application) {

    private val goodsManager: GoodsManager = GoodsManager()

    val cateListLiveData = MutableLiveData<HttpResponseBody<CateListResponse>>()

    val goodsListLiveData = MutableLiveData<HttpResponseBody<GoodsListResponse>>()
    val goodsLabelLiveData = MutableLiveData<HttpResponseBody<GoodsLabelResponse>>()

    /**
     * 分类列表(默认一级)
     */
    fun categoryList(pid: Int = 0, level: Int = 1) {
        setRxLifeScope(object : SubscribeViewModel<CateListResponse>(cateListLiveData) {
            override fun onSuccess(resp: CateListResponse) {
                super.onSuccess(resp.apply {
                    this.data.sortBy { it.label_text.isNullOrEmpty() }
                    this.level = level
                })
            }
        }) {
            goodsManager.categoryList(pid)
        }
    }

    /**
     * 物品列表
     * */
    fun goodsList(goodsRequest: GoodsRequest) {
        setRxLifeScope(SubscribeViewModel(goodsListLiveData)) {
            val maps: Map<String, String?> =
                GsonUtils.fromJson<Map<String, String?>>(
                    GsonUtils.toJson(goodsRequest),
                    Map::class.java
                ).filter { it.value != null }
            goodsManager.goodsList(maps)
        }
    }

    /**
     * 商品标签
     * */
    fun goodsService() {
        setRxLifeScope(SubscribeViewModel(goodsLabelLiveData)) {
            goodsManager.goodsService()
        }
    }

    val goodsDetailsLiveData = MutableLiveData<HttpResponseBody<GoodsDetailsResponse>>()
    fun goodsInfo(goodsId:Int) {
        setRxLifeScope(SubscribeViewModel(goodsDetailsLiveData)) {
            goodsManager.goodsInfo(goodsId)
        }
    }
}